/*
 * 意见反馈管理
 * @author 曾文
 * @time 2018/9/26
 * @since 1.0.0
 * */
import React from 'react'
import { connect } from 'dva'
import { Form,Modal,message,Tabs,Table,Spin} from 'antd'
import { Link, hashHistory } from 'dva/router'
import FlagBtn from 'widget/FlagBtn/FlagView'
import config from 'config/config'
import { mapStateToProps } from 'utils/view_utils'
import styles from './gameConfigListStyle.less'
import ListPage from 'widget/PageTmpl/ListPage'
import { Button } from 'antd/lib/radio';
import { func } from 'prop-types'
import {CopyToClipboard} from 'react-copy-to-clipboard';
const { TabPane } = Tabs;
const confirm = Modal.confirm;
import classnames from 'classnames/bind'
let cx = classnames.bind(styles)

let subElements = JSON.parse(localStorage.getItem('navBar')).subElements
const routeView = function ({ dispatch, model, form }) {

    const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
    const { modelObj, namespace } = model
    let {gameTypeList,gameActivityTypeId,zmzjCode,zysqCode,showModal,TypeModalFlag,imgLoading} = modelObj

    const columns = [
      {
        title: '游戏名称',
        dataIndex: 'gameName',
        key: 'gameName',
      },
      {
        title: '游戏描述',
        dataIndex: 'description',
        key: 'description',
      },
    ]
    let choiceType = ''
    let gameType = ''
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        choiceType = selectedRows[0].id
        gameType = selectedRows[0].type
        console.log(choiceType)
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };
    let statusList = [
      { value: 0, label: '未发布' },
      { value: 1, label: '未开始' },
      { value: 2, label: '进行中' },
      { value: 3, label: '已结束' },
    ]
    function urlSkip(url,item){
      if(!item.gameActivityId){
        message.warning('无活动Id')
        return
      }
      hashHistory.push({
        pathname: `/home/advertisementAdmin/${url}`,
        query: {
          gameStatus: 'edit',
          gameActivityId:item.gameActivityId, 
          gameType:item.gameType,
        }
      })
    }

    function showTypeModal(){
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { TypeModalFlag:true }
    });
    }
    function hideTypeModal(){
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { TypeModalFlag:false }
    });
    }
    // function editGameConfig(id){
    //   hashHistory.push({
    //     pathname: `/home/advertisementAdmin/gameStatusEdit`,
    //     query: {gameActivityId:id}
    //   })
    // }
    function infoRelease(id){
      dispatch({
        type: `${namespace}/release`,
        payload:{
          id,
        }
      })
    }
    function activityCancel(id){
      dispatch({
        type: `${namespace}/activityCancel`,
        payload:{
          id,
        }
      })
    }
    function dispalyImg(id,data){
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {
          zmzjCode:'',
          zysqCode:''
        }
      });
      let zysqPage = `subPackages3/pages/gameManage/gameTransferStation/gameTransferStation`
      let zmzjPage = `subPackages3/pages/gameManage/gameTransferStation/gameTransferStation`
      let page = `subPackages3/pages/gameManage/gameTransferStation/gameTransferStation`

      /*if(data.gameType == '1') {
        zysqPage = `subPackages3/pages/gameManage/wheel/game`
        zmzjPage = `subPackages3/pages/gameManage/wheel/game`
        page = `subPackages3/pages/gameManage/wheel/game`
      }*/

      if(!id) {
        id = data.gameActivityId
      }

      console.log(id);

      dispatch({
        type: `${namespace}/generateQrCode`,
        payload:{
          gameActivityId:id,
          params:{
            gameActivityId:id,
            gameType:data.gameType
          },  
          zysqPage: zysqPage,
          zmzjPage: zmzjPage,
          page: page
        }
      })
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { showModal:true }
    });
    }
    function hideModal(){
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { showModal:false }
    });
    }
    function deleteData(id,data){
      confirm({
        title: '删除确认',
        content: '您真的要删除此活动信息吗?',
        okText: '确认',
        okType: 'primary',
        cancelText: '取消',
        onOk() {
            // debugger
          if(data.status==0||data.status==3){
          dispatch({
            type: `${namespace}/delGameList`,
            payload:{
              id,
            }
          })
        }else{
          message.warning('只能删除未发布和已结束的活动')
        }
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    }

      // 分页表格属性配置
  let pageProps = {
    // ---------- 界面部分 ----------
    'ui': {
      // 页面接口地址
      'api_url': 'mideadc-game-center-service/activity/gameActivity/list',
      // "api_url": "admin/housetype/list",
      "data_field_name":"result.records",
      "data_pageNo":"result.current",
      "data_pageSize":"result.size",
      "data_total":"result.total",
      // 接口方式
      'method': 'GET',
      'app': 'isales-mgmt-application',
      // 接口参数
      'params': '',
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      'mockData': null,
      // 查询栏
      'search_bar': {
        'fields': [
          {
            en_name: 'gameActivityTypeId',
            zh_name: '活动类型',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: gameTypeList,
          },
          {
            en_name: 'status',
            zh_name: '活动状态',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: statusList,
          },
          {
            en_name: 'title',
            zh_name: '活动名称',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
          {
            en_name: 'createPerson',
            zh_name: '创建人',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
        ],
        searchHandler: (p) => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click', p)
        },
        resetHandler: (p) => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click', p)
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        // pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
        //   'carName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        // ]
      },
      // 数据表格
      'table': {
        'status_params': 'status=0',
        'status_text': '全部',
        'scroll': { x: 2000 },
        'action_props': { width: 200 },
        // 表头字段列表"
        'fields': [
          {
            en_name: "key",
            zh_name: "序号",
            width: 60,
            render: (a, item, index, d, e, f) => {
              return index + 1
            },
          },
          {
            'en_name': 'gameName',
            'zh_name': '游戏名称',
            width: 120
          },
          {
            'en_name': 'title',
            'zh_name': '活动名称',
            
            width: 200,
            render: (a, item, index, d, e, f) => {
              return (
              <span>
              <FlagBtn node={<a style={{color:"#0877FD"}} onClick={() => {urlSkip('gameParamsTab',item)}}>{item.title}</a>} btnId={''}> </FlagBtn>
              </span>
              )
            },
          },
          {
            'en_name': 'startTime',
            'zh_name': '活动时间',
            width: 200,
            render: (text, item) => {
              return <div>{`${item.startTime.split(' ')[0] || ''}${item.endTime && ' ~ ' || ''}${item.endTime.split(' ')[0] || ''}`}</div>
           }
          },
          {
            'en_name': 'status',
            'zh_name': '活动状态',
            width: 100,
            render: (a, item, index, d, e, f) => {
              if(item.status=='0'){
                return <div>未发布</div>
              }
              else if(item.status=='1'){
                return <div>未开始</div>
              }
              else if(item.status=='2'){
                return <div>进行中</div>
              }
              else if(item.status=='3'){
                return <div>已结束</div>
              }else{
                return <div>-</div>
              }
            }
          },
          {
            'en_name': 'createPerson',
            'zh_name': '创建人',
            width: 200,
            // render: (a, item, index, d, e, f) => {
            // }
          },
          {
            'en_name': 'createTime',
            'zh_name': '创建时间',
            width: 200,
            // render: (a, item, index, d, e, f) => {
            // }
          },
          {
            'en_name': 'actualNumber',
            'zh_name': '参与数',
            width: 150,
          },
          {
            'en_name': 'type',
            'zh_name': '推广模式',
            width: 150,
            render: (a, item, index, d, e, f) => {
              if(item.type==1){
                return <div>项目推广</div>
              }
              else if(item.type==2||item.type==3){
                return <div>非项目推广</div>
              }else{
                return <div>-</div>
              }
            }
          },
          {
            'en_name': 'link',
            'zh_name': '链接',
            width: 90,
            fixed:'right',
            render: (a, item, index, d, e, f) => {
              if(item.title){
                let url = `/subPackages3/pages/gameManage/gameTransferStation/gameTransferStation?gameActivityId=${item.gameActivityId}`
                if(item.gameType == 1) {
                  url = `/subPackages3/pages/gameManage/wheel/game?gameActivityId=${item.gameActivityId}`
                }
                return (
                  <CopyToClipboard text={url}
                    onCopy={() => {
                      message.success('复制成功')
                    }}>
                    <a style={{color:"#0877FD"}}>复制链接</a>
                  </CopyToClipboard>
                )
              }
            }
          },
          {
            en_name: 'edit',
            zh_name: '操作',
            width: 200,
            fixed:'right',
            render: (a, item, index, d, e, f) => {
              return (
                <span>
                  <FlagBtn node={<a onClick={() => {dispalyImg(item.gameActivityId,item)}}>预览<span className="ant-divider" style={{ display: 'inline-block' }} /></a>} btnId={''}> </FlagBtn>
                  {(item.releaseStatus==0)&&<FlagBtn node={<a onClick={() => {infoRelease(item.gameActivityId)}}>发布<span className="ant-divider" /></a>} btnId={''}> </FlagBtn>}
                  {item.releaseStatus==1&&<FlagBtn node={<a onClick={() => {activityCancel(item.gameActivityId)}}>取消发布<span className="ant-divider" /></a>} btnId={'20802'}> </FlagBtn>}
                  <FlagBtn node={<a onClick={() => {urlSkip('playerInfoList', item)}}>玩家<span className="ant-divider" /></a>} btnId={'20803'}> </FlagBtn>
                  <FlagBtn node={<a onClick={() => {urlSkip('winningInfoList', item)}}>奖品<span className="ant-divider" /></a>} btnId={'20804'}> </FlagBtn>
                  {/* <FlagBtn node={<a onClick={() => {}}>统计<span className="ant-divider" /></a>} btnId={'20503'}> </FlagBtn> */}
                  {/* <FlagBtn node={<a onClick={() => {}}>复制链接<span className="ant-divider" /></a>} btnId={'20503'}> </FlagBtn> */}
                  <FlagBtn node={<a onClick={() => {urlSkip('gameParamsTab', item)}}>编辑<span className="ant-divider" /></a>} btnId={'20805'}> </FlagBtn>
                  <FlagBtn node={<a onClick={() => {deleteData(item.gameActivityId,item)}}>删除<span className="ant-divider" /></a>} btnId={'20806'}> </FlagBtn>
                </span>
              )
            },
          },
        ],
      },
      // 操作栏
      action_bar: [
        {
          'func_name': 'add',
          'label': '新建活动',
          btnId: '20801',
          'type': 'primary',
          'onClick': (e) => {
            showTypeModal()
            // hashHistory.push({
            //   pathname: '/home/advertisementAdmin/gameParamsTab',
            //   query: { gameActivityTypeId: gameActivityTypeId}
            // })
          }
        },
      ],
    },
  }
  if (!!modelObj.biz) {
    pageProps.biz = modelObj.biz
    pageProps.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz }
      })
    }
  }
    return (
        <div className={cx('pageLayout')}>
            <ListPage pageProps={pageProps} />
            <Modal
                   title="活动类型"
                   maskClosable={true}
                   onCancel={()=>{hideTypeModal()}}
                   onOk={()=>{
                     {/* debugger */}
                    if(!choiceType){
                       message.warning('请选择游戏类型')
                       return
                     }
                      hashHistory.push({
                          pathname: '/home/advertisementAdmin/gameParamsTab',
                          query: { gameActivityTypeId: choiceType, gameType: gameType}
                      })
                      hideTypeModal()
                   }}
                   visible={TypeModalFlag}
                   >
                   <Table
                   pagination={false}
                   rowSelection={{ type:'radio',...rowSelection}}
                   columns={columns}
                   dataSource={gameTypeList}
                   />
            </Modal>
            <Modal
                   maskClosable={true}
                   onCancel={()=>{hideModal()}}
                   visible={showModal}
                   footer={null}>
            <Tabs defaultActiveKey="1" size={'small'}>
              <TabPane tab="美的置业云" key="1">
                {
                  imgLoading?                  
                  <div className={cx('codeClass')}>
                    <Spin tip='Loading...' size='large'></Spin>
                  </div> :
                  <img className={cx('codeClass')} src={zmzjCode}/>
                }
                  
                </TabPane>
              {/* <TabPane tab="置业神器" key="2">
                {
                  imgLoading? 
                  <div className={cx('codeClass')}>
                    <Spin tip='Loading...' size='large'></Spin>
                  </div> :
                  <img className={cx('codeClass')} src={zysqCode}/>
                }
              </TabPane> */}
            </Tabs>
            </Modal>
        </div>
    )
}
export default connect(mapStateToProps)(Form.create()(routeView))